import request from '@/utils/request.js'
import { useTokenStore } from '@/stores/token'

// 注册服务
export const registerService = async (registerData) => {
    // 创建 URLSearchParams 实例用于构建表单数据
    const params = new URLSearchParams(); 

    // 遍历注册数据对象的所有键值对
    for (const [key, value] of Object.entries(registerData)) {
        if (value) { // 确保值不为空
            params.append(key, value);
        }
    }

    try {
        const response = await request.post('/user/register', params); //POST请求
        return response; // 返回响应结果
    } catch (error) {
        console.error('注册失败:', error);
        throw error; // 重新抛出错误以便后续处理
    }
}

// 登录服务
export const loginService = async (loginData) => {
    const params = new URLSearchParams();

    // 仅处理非空的登录数据
    for (const [key, value] of Object.entries(loginData)) {
        if (value) { // 确保值不为空
            params.append(key, value);
        }
    }

    try {
        const response = await request.post('/user/login', params);
        return response; // 返回响应结果
    } catch (error) {
        // console.error('登录失败:', error);
        throw error; // 重新抛出错误以便后续处理
    }
}

//获取个人信息
export const userInfoGetService = ()=>{
    return request.get('/user/userInfo');
}

//更新个人信息
export const userInfoUpdateService = (userInfo) => {
    const tokenStore = useTokenStore();
    return request.put('/user/update', 
        userInfo,  // 直接发送 JSON 对象
        { 
            headers: { 
                'Authorization': tokenStore.token,
                'Content-Type': 'application/json'  // 修改为 JSON 格式
            } 
        }
    );
}

//更新头像
export const userAvatarUpdateService = (avatarUrl) => {
    const tokenStore = useTokenStore();
    const params = new URLSearchParams();
    params.append('avatarUrl', avatarUrl);
    
    return request.patch('/user/updateAvatar', 
        params,
        { 
            headers: { 
                'Authorization': tokenStore.token,
                'Content-Type': 'application/x-www-form-urlencoded'
            } 
        }
    );
}

// 修改更新密码的函数
export const updatePassword = (passwordData) => {
    const tokenStore = useTokenStore();
    const params = {
        old_pwd: passwordData.old_pwd,
        new_pwd: passwordData.new_pwd,
        re_pwd: passwordData.re_pwd
    };
    
    return request.patch('/user/updatePwd', 
        params,
        { 
            headers: { 
                'Authorization': tokenStore.token,
                'Content-Type': 'application/json'
            } 
        }
    );
}

// 获取用户信息
export function getUserInfo() {
    return request({
        url: '/api/user/info',
        method: 'get'
    })
}

